import { Component, OnInit,Input,ViewChild } from '@angular/core';
import {Router,NavigationExtras,ActivatedRoute} from '@angular/router';
import { ClueService } from '../../../../../@core/service/typescript-angular-client/api/clue.service';
import { ClueDataService } from '../../../../../@core/service/clue-service/clue-data.service';
import { CaseService } from '../../../../../@core/service/handle-service/api/case.service';
 
import { NzFormatEmitEvent } from 'ng-zorro-antd/core';
import { OrgService } from '../../../../../@core/service/person-select-service/api/org.service';
import { StakeHolderService } from '../../../../../@core/service/handle-service/api/stakeHolder.service';
import { CaseDocModel } from '../../../../../@core/service/handle-service/model/caseDocModel';

import * as moment from 'moment'
import { UUID } from 'angular2-uuid';
import { map } from 'rxjs/operators';
import { getTestBed } from '@angular/core/testing';

@Component({
  selector: 'app-edithandle',
  templateUrl: './edithandle.component.html',
  styleUrls: ['./edithandle.component.scss']
})
export class EdithandleComponent implements OnInit {

  
  @ViewChild('clickEvent') myclick;
  @ViewChild('orgTree') orgTree;
    //区域数据
    public areaData: any;
    //省级联动
    public provinces:any[];
    //市级联动
    public cities:any[];
    //县级联动
    public counties:any[];

    public sendMsg:any;

    public stakerHolder:any[]=[];
    public stakerHolderList:any[];

    public id:any;
    private docid:string;
    public desk: any;

    public list;
   
    addressDetails: any[]=[];
    private session = sessionStorage;
    expandKeys = ['0-0'];  // 默认展开的节点
    value: string;
    nodes = [];
    listOfOption = [];
    personOptionList = [];
    getPersonSelectedValue = [];
    public date = new Date();

  constructor(
    public active:ActivatedRoute,
    public clue:ClueService,
    public router:Router,
    public clueData:ClueDataService,
    private caseService: CaseService,
    private orgService: OrgService,
    private stakeHolderService: StakeHolderService) {
      this.areaData = clueData.area;
  }
  public flag:boolean=false;
  public flags:boolean=false;
  public sortValue:any="1001";
  public providerType = "0";

  public userName = window.sessionStorage.getItem('userName');

  public selectValue:any=[{
    name:"法人",value:"0"
  },{
    name:"个人",value:"1"
  }];

  // 案件新增字段
  public caseList:any = {
    "cmsCase": {
      "id": null,                          // 主表id
      "registerCode": null,                // 登记号
      "sourceType": "1001",                // 来源分类
      "provider": {},                      // 案源提供人信息
      "partyName": "",                     // 当事人名称
      // "clueId": null,
      "registrant": {
        "orgId": "",
        "orgName": "",
        "registerName": ""
      },
      "partyAddress": {
        "province":null,"city":null,"county":null
      },                                   // 当事人地址
      "partyAddressDetail": "",            // 当事人详细地址
      "addressDetail": "",                 // 当事人地址
      "partyPhone": "",                    // 当事人电话
      "partyOtherPhone": "",               // 当事人其他电话
      "enrollmentContent": "",             // 案源登记内容
      "enrollmentRemark": "",              // 案源登记备注
      "currentLink": "线索",                // 当前所处阶段
      "currentHandlePerson": "",           // 当前处理人
      "currentStatus": "办理中",            // 当前所处状态
      "createdAt": ""                      // 登记时间
    },
    docId: null                            // 文书id
  }

  public caseProviderstring="";
  public addressstring="";

  public myDoc:any;
  public myflag:boolean;

  ngOnInit() {
    this.id = this.active.snapshot.params["id"];
    this.docid = this.active.snapshot.params["docid"];
    this.desk = this.active.snapshot.params["desk"];
    this.provinces = this.areaData;
    let nodesData = JSON.parse(this.session.getItem('areaData'));
    this.nodes = this.DataProcess(nodesData, '0', '机构');
    this.getCaseData(this.id);
  }

  // 获取案件信息
  getCaseData(id) {
    this.caseService.caseIdIdGet(id).subscribe(data=>{
        this.list = data.data;
        if( this.list){
        this.sendMsg = this.list;
        // 编辑赋值
        if(this.list.createdAt){
          let datetime = moment(this.list.createdAt).format('YYYY-MM-DD hh:mm:ss');
          this.caseList.cmsCase.createdAt = datetime;
        }else{
          this.caseList.cmsCase.createdAt = null
        }//日期
        this.caseList.cmsCase.registerCode=this.list.registerCode//登记号
        this.caseList.cmsCase.registrant = this.list.registrant;// 案件办理人
        console.log(this.caseList.cmsCase.registrant)
        let parentId: string;
        for (let i = 0; i < this.nodes.length; i++) {
          let children = this.nodes[i]['children'];
          for (let k = 0; k < children.length; k++) {
            if (this.list.registrant.orgId === children[k]['value']) {
              parentId = children[k]['parentId'];
            }
          }
        }
        this.expandKeys = [parentId, this.list.registrant.orgId];
        this.caseList.cmsCase.sourceType = this.list.sourceType;//来源分类
        this.caseList.cmsCase.provider = JSON.parse(this.list.provider) //案源提供人
        this.caseList.cmsCase.partyName = this.list.partyName;
        // 判断是否有地址
        if(this.list.partyAddress){
          this.caseList.cmsCase.partyAddress = JSON.parse(this.list.partyAddress) //地区赋值
          this.provinces =  this.areaData
          let province,city,county,detailed;
          //查找返回省级列表
          this.list.partyAddress = JSON.parse(this.list.partyAddress)
  
          if(this.list.partyAddress.province==this.provinces[0]['key']){
              province =this.list.partyAddress.province;
              this.addressDetails[0] = this.provinces[0].label
          }else{
              province = null;
          }
          //查找返回市级列表
          if(this.list.partyAddress.city){
            this.cities = this.provinces[0].children;
            city = this.list.partyAddress.city;
            this.addressDetails[1] = this.cities.filter(cityF=>cityF.key == city)[0].label
  
          }else{
            this.cities = [];
            city =null;
          }
          //查找返回县级列表
          if(this.list.partyAddress.county){
            this.counties = this.cities.filter(cityItem=>city ==cityItem.key)[0].children;
            county = this.list.partyAddress.county;
            this.addressDetails[2] = this.counties.filter(countyF=>county == countyF.key)[0].label
  
          }else{
            this.counties = [];
            county =null;
          }
        }
       
        this.caseList.cmsCase.partyAddressDetail = this.list.partyAddressDetail//详细地址
        this.caseList.cmsCase.partyPhone = this.list.partyPhone//当事人联系电话
        this.caseList.cmsCase.partyOtherPhone = this.list.partyOtherPhone//当事人其他联系方式
        this.caseList.cmsCase.enrollmentContent = this.list.enrollmentContent//案源登记内容
        this.caseList.cmsCase.enrollmentRemark = this.list.enrollmentRemark//案件备注
      }
    })
  }
  //省级选择
  onProvinceChange(event){
   if(event!==null){
      this.caseList.cmsCase.partyAddress.city = null;
      this.caseList.cmsCase.partyAddress.county = null;
      this.caseList.cmsCase.partyAddressDetail = "";
      this.cities = this.provinces[0].children;
      this.addressDetails[0] = this.provinces[0].label;
      this.addressDetails[1] = this.addressDetails[2] = "";
    }else{
      this.caseList.cmsCase.partyAddress.province = null;
      this.caseList.cmsCase.partyAddress.city = null;
      this.caseList.cmsCase.partyAddress.county = null;
      this.caseList.cmsCase.partyAddressDetail = "";
      this.addressDetails[0] =this.addressDetails[1] = this.addressDetails[2] = "";
      this.cities = [];
      this.counties = [];
    }
  }
  //市级选择
  onCityChange(event){
    if(event!==null){
      this.caseList.cmsCase.partyAddress.county = null;
      this.caseList.cmsCase.partyAddressDetail = "";
      let currCity= this.cities.filter(city=>city.key==event);
      this.counties = currCity[0].children;
      this.addressDetails[1] = currCity[0].label;
      this.addressDetails[2] = "";
    }else{
      this.caseList.cmsCase.partyAddress.city = null;
      this.caseList.cmsCase.partyAddress.county = null;
      this.caseList.cmsCase.partyAddressDetail = "";
      this.addressDetails[1] = this.addressDetails[2] = "";
      this.counties = [];
    }
  }
  //县级选择
  onCountyChange(event){
    if(event!==null){
      let currCounty = this.counties.filter(county=>county.key==event);
      this.addressDetails[2] = currCounty[0].label;
    }else{
      this.caseList.cmsCase.partyAddress.county = null;
      this.caseList.cmsCase.partyAddressDetail = "";
      this.addressDetails[2]='';
    }
  }

  /**
   * 选择登记人 等级机关
   *  */ 
  // 将后台返回的数据处理成符合树形结构 

  DataProcess(data, parentId, type) {
    let arrayList = [];
    for(var i = 0; i < data.length; i++) {
      if (data[i]['orgTypeName'] == type && data[i]['orgParentId'] == parentId) {
        let obj = {
          'title': '', 
          'text': '',
          'value': '', 
          'key': '', 
          'parentId': '', 
          'officeCode': '',
          'children': []
        };
        obj.title = data[i]['orgName'] || "";
        obj.text = data[i]['orgName'] || "";
        obj.value = data[i]['orgId'] || "";
        obj.key = data[i]['orgId'] || "";
        obj.parentId = data[i]['orgParentId'] || "";
        obj.children = this.DataProcess(data, obj.value, '机构');
        if (obj.children.length <= 0) {
          obj['isLeaf'] = true;
        }
        arrayList.push(obj);
      }
    }
    return arrayList;
  }
  // 获取树中选中的节点
  getSelectedNodeList(key): void {

    let nodesData = JSON.parse(this.session.getItem('areaData'));
    this.listOfOption = this.DataProcess(nodesData, key, '部门');
  }

  // 获取部门选择框选中的节点 并查询人员
  getSelectedValue(value): void {
    this.personOptionList = [];
    let token = this.session.getItem("accessToken") || "";
    for (let i = 0; i < this.listOfOption.length; i++) {
      if (this.listOfOption[i]['officeId'] == value) {
        this.getPerson(token, this.listOfOption[i]['officeCode']);
      }
    }
  }

  // 获取人员信息
  getPerson (token, officeCode, userId?:string) {
    this.orgService.getUserByAreaId(token, officeCode).subscribe((data) => {
      if (data['rel'] == true) {
        this.personOptionList=[];
        for (let i = 0; i < data['data'].length; i++) {
          let obj = {'realName': '','positionCode': '',userId:""};
          obj.realName = data['data'][i]['realName'] || "";
          obj.positionCode = data['data'][i]['positionCode'] || "";
          obj.userId = data['data'][i]['userId'] || "";
          this.personOptionList.push(obj);
        }
      }
    }, (error) => {
    });
  }

  // 去掉传参中value值为空的数据

  removeEmptyData(data: object) {
    for (let key in data) {
      if (typeof(data[key.toString()]) == 'object') {
        this.removeEmptyData(data[key]);
      } else if (!data[key.toString()]) {
        delete data[key.toString()];
      }
    }
  }

  // 选择线索来源  表单改变
  radiochang(e) {
    if(e == "1001"){
      this.caseList.cmsCase.provider={
        "jcr1":"", "ssdw1":"","jcr2":"","ssdw2":""
      }
    }else if(e == "1003"||this.sortValue == "1004" ||this.sortValue == "1005"){
      this.caseList.cmsCase.provider={
        "depname":"","atten":"","telnum":"","address":""
      }
    }else if(e == "1002"){
      this.caseList.cmsCase.provider={
        "type":"0","depname":"","pic":"","telnum":"","address":"","otherinfo":""
      }
     this.providerTypeChange(event);
    }
  }
  providerTypeChange(event):void {
    if(event=="0"){
      this.caseList.cmsCase.provider={
        "type":"0","depname":"","pic":"","telnum":"","address":"","otherinfo":""
      }
    }else if(event=="1"){
      this.caseList.cmsCase.provider={
        "type":"1","name":"","idnum":"","telnum":"","address":"","otherinfo":""
        }
    }
  }
  // 查询地区
  findArea(areas,parentId,areaName,areaId){
  for(let i = 0; i<areas.length;i++){
      if(areas[i].areaParentId == parentId){
          areaName.push(areas[i].areaName);
          areaId.push(areas[i].areaId);
          this.findArea(areas,areas[i].areaId,areaName,areaId) 
      }
  }
  }
  // 查询地区Code  
  findAreaCode(areas,areaId){
    for(let i =0;i<areas.length;i++){
      if(areas[i].areaId == areaId){
          return areas[i].areaCode;
      }
    }
  }
  // 提交
  mysubmit(callback){
    let oldCaseList = new Object();
    oldCaseList = this.caseList; 
    if(this.caseList.cmsCase.createdAt){
      let datetime = moment(this.caseList.cmsCase.createdAt).format('YYYY-MM-DD HH:mm:ss')
      this.caseList.cmsCase.createdAt = datetime
    }else{
      this.caseList.cmsCase.createdAt = ''
    }
    this.caseList.cmsCase.id = this.list.id;
    let partyAddress = typeof(this.caseList.cmsCase.partyAddress) == 'string' ? 
                        this.caseList.cmsCase.partyAddress :
                        JSON.stringify(this.caseList.cmsCase.partyAddress);

    let provider = typeof(this.caseList.cmsCase.provider) == 'string' ?
                        this.caseList.cmsCase.provider : 
                        JSON.stringify(this.caseList.cmsCase.provider);

    this.caseList.cmsCase.partyAddress = partyAddress;
    this.caseList.cmsCase.provider = provider;
    // 获取登记组织名称
    let orgTreeNode = this.orgTree.getSelectedNodeList()[0]['origin'];
    this.caseList.cmsCase.registrant.orgName = orgTreeNode['text'];
    this.caseList.cmsCase.currentHandlePerson = this.session.getItem('userId');
    this.caseList.cmsCase.addressDetail = this.addressDetails[0] 
                                          + this.addressDetails[1] 
                                          + this.addressDetails[2]
                                          + this.caseList.cmsCase.partyAddressDetail;
                                          
    this.caseList.docId = this.docid;


     // 新增5条当前办理人信息
     let sourceDeptId = '',sourceOrgName = '',areaName=[],areaId=[],sourceOrgId;
     let organization = JSON.parse(this.session.getItem('organizations'))[0];
     // 获取行政区划
     let areas = JSON.parse(this.session.getItem('areas'));
     sourceOrgId = organization['orgId']
     sourceOrgName = organization['orgName'];
     // 查询地区
     this.findArea(areas,'0',areaName,areaId);


     // 当前办理人名字
     this.caseList.cmsCase.currentHandlePersonName = sessionStorage.getItem('realName');
     // 当前办理人所属机构id
     this.caseList.cmsCase.currentHandleOrgId = sourceOrgId;
     // 当前办理人所属机构名称
     this.caseList.cmsCase.currentHandleOrgName = sourceOrgName;
     // 当前办理人所属地区编号
     this.caseList.cmsCase.currentHandleAreaNo = this.findAreaCode(areas,areaId[areaId.length-1]);
     // 当前办理人所属地区名称
     this.caseList.cmsCase.currentHandleAreaName = areaName[areaName.length-1];

    var list:any = typeof(this.caseList) == 'string' ? JSON.stringify(this.caseList) : this.caseList;
    console.log(list);
    this.caseService.casePut(list).subscribe((data) => {
      this.caseList.cmsCase.provider = JSON.parse(this.caseList.cmsCase.provider)
      this.caseList.cmsCase.partyAddress = JSON.parse(this.caseList.cmsCase.partyAddress)
      if (data['rel']) {
        if(this.desk == 'handle'){
          this.router.navigate(['/main/home/handle/previewdocument', this.id]);
        }else{
          this.router.navigate(['/main/home/handle/detailsteps',this.id,'handle','other']);
        }
        this.flag = true
        this.flags = false;
      } else {
        this.flag = false
        this.flags = true;
      }
      this.caseList = oldCaseList;
    }, (error) => {
      this.caseList = oldCaseList;
    })
  }


  dodoc(e){
    if(e){
      this.myDoc=e;
      this.myflag = true;
    }else{
      this.myflag = false;
    }
  }
  emitFather(){
    console.log('要弹框！！！！！！！');
  }
  fun(ev){
    this.myflag = ev;
  }

}
